package com.example.demo.service;

import com.example.demo.domain.send.DingMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author lizijian
 */
@Slf4j
@Component
public class SendDingMessageService {
  private static final String GET_DATA_DING_URL ="https://oapi.dingtalk.com/robot/send?access_token=9ae9e13b974c8a431029653058b5ace75773b47466e2d9e206f4b54673ff3051";
  private static final String ERROR_DING_URL ="https://oapi.dingtalk.com/robot/send?access_token=4b7c58e798e3b6d067da271e207fae741e799d7d34c5a6c1e97042087bf6e0bd";

  private static String environment;

  @Value("${spring.profiles.active}")
  public  void setEnvironment(String environment) {
    SendDingMessageService.environment = environment;
  }

  /**
   * 发送爬虫通知
   */
  public static void sendGetDataMessage(DingMessage message){
    try {
      message.setText(environment+"-爬虫通知:"+message.getText());
      HttpClient httpclient = HttpClients.createDefault();
      HttpPost httppost = new HttpPost(GET_DATA_DING_URL);
      httppost.addHeader("Content-Type", "application/json; charset=utf-8");
      StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
      httppost.setEntity(se);
      HttpResponse response = httpclient.execute(httppost);
      log.info("DingResponse:" + EntityUtils.toString(response.getEntity()));
    }catch (Exception e){
      log.error("发送钉钉爬虫通知失败");
      log.info("errorMessage:"+e.getMessage());
    }
  }

  public static void sendErrorMessage(DingMessage message){
    try {
      message.setText(environment+"-异常通知:"+message.getText());
      HttpClient httpclient = HttpClients.createDefault();
      HttpPost httppost = new HttpPost(ERROR_DING_URL);
      httppost.addHeader("Content-Type", "application/json; charset=utf-8");
      StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
      httppost.setEntity(se);
      HttpResponse response = httpclient.execute(httppost);
      log.info("DingResponse:" + EntityUtils.toString(response.getEntity()));
    }catch (Exception e){
      log.error("发送钉钉异常通知失败");
      log.info("errorMessage:"+e.getMessage());
    }
  }
}
